package com.cts.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cts.entity.Blog;
import com.cts.entity.Tag;
import com.cts.mapper.BlogTagMapper;
import com.cts.model.dto.BlogListDTO;
import com.cts.model.vo.*;
import com.cts.service.BlogService;
import com.cts.mapper.BlogMapper;
import com.cts.service.BlogTagService;
import com.cts.util.DateFormatUtils;
import com.cts.util.DictUtils;
import com.mysql.cj.util.StringUtils;
import javafx.scene.input.DataFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.time.LocalDateTime;
import java.util.*;

/**
* @author tongshengchen
* @description 针对表【blog】的数据库操作Service实现
* @createDate 2023-02-06 18:30:39
*/
@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService{

    @Autowired
    BlogMapper blogMapper;

    @Autowired
    DictUtils dictUtils;

    @Autowired
    BlogTagMapper blogTagMapper;

    @Autowired
    DateFormatUtils dateFormatUtils;

    @Override
    public PageResultVO<Blog> getBlogList(BlogListDTO blogListDTO) {
        LambdaQueryWrapper<Blog> blogWrapper = new LambdaQueryWrapper<>();
        blogWrapper.like(!StringUtils.isNullOrEmpty(blogListDTO.getTitle()), Blog::getTitle, blogListDTO.getTitle())
                .like(!Objects.isNull(blogListDTO.getCategoryId()), Blog::getCategoryId, blogListDTO.getCategoryId());
        Page<Blog> page = new Page<>(blogListDTO.getPageNo(), blogListDTO.getPageSize());
        Page<Blog> blogPage = blogMapper.selectPage(page, blogWrapper);
        List<Blog> records = blogPage.getRecords();
        ArrayList<Blog> blogs = new ArrayList<>();

        // 获取分类字典值
        log.info("码值映射开始...");
        Map<Long, String> cateGoryDict = dictUtils.getCateGoryDict();
        for (Blog record : records) {
            record.setCategoryName(cateGoryDict.get(record.getCategoryId()));
            log.info("文章{}的分类名称为：{}" , record.getTitle(), record.getCategoryName());
            blogs.add(record);
        }
        log.info("码值映射结束...");

        return new PageResultVO<>(blogPage.getTotal(), blogs);
    }


    @Override
    public Boolean publishBlog(Integer id, Boolean isPublished) {
        Boolean flag = blogMapper.publishBlog(id, isPublished);
        return flag;
    }

    @Override
    public Boolean topBlog(Integer id, Boolean isTop) {
        Boolean flag = blogMapper.topBlog(id, isTop);
        return flag;
    }

    @Override
    public void privateVisible(Long id) {
        blogMapper.privateVisible(id);
    }

    @Override
    public void updateVisible(Blog blog) {
        blogMapper.updateVisible(blog);
    }

    @Override
    public Blog setBlogDefault(Blog blog) {

        // 设置默认值
        if(Objects.isNull(blog.getIsPublished())) {
            blog.setIsPublished(false);
        }
        if(Objects.isNull(blog.getIsTop())) {
            blog.setIsTop(false);
        }
        if(Objects.isNull(blog.getCreateTime())) {
            blog.setCreateTime(LocalDateTime.now());
        }
        if(Objects.isNull(blog.getIsAppreciation())) {
            blog.setIsAppreciation(false);
        }
        if(Objects.isNull(blog.getIsRecommend())) {
            blog.setIsRecommend(false);
        }
        if(Objects.isNull(blog.getIsCommentEnabled())) {
            blog.setIsCommentEnabled(false);
        }
        if(Objects.isNull(blog.getViews())) {
            blog.setViews(0);
        }
        if(Objects.isNull(blog.getWords())) {
            blog.setWords(blog.getContent().length());
        }
        if(Objects.isNull(blog.getReadTime())) {
            blog.setReadTime(blog.getWords()/200);
        }
        blog.setUpdateTime(LocalDateTime.now());

        return blog;
    }


    @Override
    public List<RandomBlogVO> getRandomBlogs() {
        List<RandomBlogVO> randomBlogs = blogMapper.getRandomBlogs();
        log.info("查询随机文章");
        return randomBlogs;
    }

    @Override
    public PageResultVO<BlogInfoVO> getBlogs(String type, String value, Integer pageNo, Integer pageSize) {

        Page<BlogInfoVO> blogInfoVOPage = new Page<>(pageNo, pageSize);

        IPage<BlogInfoVO> pageResult =  blogMapper.getBlogs(blogInfoVOPage, type, value);
        log.info("查询满足条件的博客");
        PageResultVO<BlogInfoVO> pageResultVO = new PageResultVO<>();
        pageResultVO.setPageData(pageResult.getRecords());
        pageResultVO.setTotal(pageResult.getTotal());

        log.info("查询博客对应的标签");
        List<BlogInfoVO> records = pageResult.getRecords();
        records.stream().forEach(record -> record.setTagList(blogTagMapper.getTagByBlog(record.getId())));
        return pageResultVO;
    }

    @Override
    public Blog getBlogDetail(Long id) {

        log.info("开始查询博客详情");
        Blog blog = blogMapper.selectById(id);
        List<Tag> tagByBlog = blogTagMapper.getTagByBlog(id);
        Map<Long, String> cateGoryDict = dictUtils.getCateGoryDict();
        String categoryName = cateGoryDict.get(blog.getCategoryId());

        log.info("封装博客内容");
        blog.setCategoryName(categoryName);
        blog.setTags(tagByBlog);
        log.info("查询完成");
        return blog;

    }

    @Override
    public Map<String, Object> getBlogTimeLine() {
        List<TimeLineVO> timeLine = blogMapper.getBlogTimeLine();
        Map<String, List<TimeLineVO>> mapTimeLine = new HashMap<>();
        for (TimeLineVO timeLineVO : timeLine) {
            String yearMon = dateFormatUtils.LocalDateTimeToString(timeLineVO.getUpdateTime(), "yyyy年MM月");
            int dayOfMonth = timeLineVO.getUpdateTime().getDayOfMonth();
            timeLineVO.setDay(dayOfMonth);
            if (mapTimeLine.containsKey(yearMon)) {
                mapTimeLine.get(yearMon).add(timeLineVO);
            }
            else{
                List<TimeLineVO> value = new ArrayList<>();
                value.add(timeLineVO);
                mapTimeLine.put(yearMon, value);
            }
        }
        log.info("时间线数据组装完成");

        Map<String, Object> res = new HashMap<>(2);
        res.put("length", timeLine.size());
        res.put("data", mapTimeLine);
        log.info("查询结果组装完成");
        return res;
    }


}




